// 自动补零
const Zero = s => (s < 10 ? `0${s}` : s);

const Dateformat = (date, formatter) => {
  let d = date;
  if (typeof d !== 'object') {
    d.replace(/-/g, '-');
    d = new Date(d);
  }
  let f = formatter || 'yyyy/MM/dd HH:mm:ss';
  const t = {};
  t.yyyy = d.getFullYear();
  t.MM = (Zero(d.getMonth() + 1));
  t.dd = Zero(d.getDate());
  t.HH = Zero(d.getHours());
  t.mm = Zero(d.getMinutes());
  t.ss = Zero(d.getSeconds());
  ['yyyy', 'MM', 'dd', 'HH', 'mm', 'ss'].forEach((item) => {
    f = f.replace(item, t[item]);
  });
  return f;
};

const changeTime = (date) => {
  let DateObj = new Date(date);
  // 将时间转换为 XX 年 XX 月 XX 日 XX 时 XX 分 XX 秒格式
  let year = DateObj.getFullYear();
  let month = DateObj.getMonth() + 1;
  let day = DateObj.getDate();
  month = month > 9? month : '0' + month;
  day = day > 9? day : '0' + day;
  return `${year}年${month}月${day}日`;
}

const setDocumentTitle = (title = 'index') => {
  if (window.document.title === title) {
    return;
  }
  document.title = title;
  const mobile = navigator.userAgent.toLowerCase();
  if (/iphone|ipad|ipod/.test(mobile)) {
    const iframe = document.createElement('iframe');
    iframe.style.display = 'none';
    // 替换成站标favicon路径或者任意存在的较小的图片即可
    iframe.setAttribute('src', '');
    // eslint-disable-next-line func-names
    const iframeCallback = function () {
      setTimeout(() => {
        iframe.removeEventListener('load', iframeCallback);
        document.body.removeChild(iframe);
      }, 0);
    };
    iframe.addEventListener('load', iframeCallback);
    document.body.appendChild(iframe);
  }
};

function randomString(length) {
  const chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  let result = '';
  for (let i = length; i > 0; i -= 1) {
    result += chars[Math.floor(Math.random() * chars.length)];
  }
  return result;
}

// 封装一个时间戳转日期的函数
function FormDateTime(date) {
  let DateObj = new Date(date);
  // 将时间转换为 XX 年 XX 月 XX 日 XX 时 XX 分 XX 秒格式
  let year = DateObj.getFullYear();
  let month = DateObj.getMonth() + 2;
  let day = DateObj.getDate();
  month = month > 9? month : '0' + month;
  day = day > 9? day : '0' + day;
  return `${year}-${month}-${day}`;
}

export default {
  Zero,
  Dateformat,
  changeTime,
  setDocumentTitle,
  randomString,
  FormDateTime
};
